package com.algo.core.filter;

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 基于SPI思想，读取解析出配置的过滤器链
 */
public class RapidFilterLoader {

    private static final Logger logger = Logger.getLogger(RapidFilterLoader.class);

    private final static String RAPID_FILTER_PATH = RapidFilterLoader.class.getResource("/").getPath()
                                                            + "META-INF/filter_config.properties";

    private final static String RAPID_FILTER_KEY = "rapid.filters.key";

    private final static String RAPID_FILTER_SEPARATOR = ",";

    private RapidFilterLoader() {}

    public static List<RapidFilter> load() throws Exception {
        InputStream is = null;
        List<RapidFilter> repidFilters = new ArrayList<>();
        try {
            logger.info("prepare load rapid filter, spi file path is ," + RAPID_FILTER_PATH + ", key is " +  RAPID_FILTER_KEY);
            is = new FileInputStream(RAPID_FILTER_PATH);
            // 加载内容
            Properties properties = new Properties();
            properties.load(is);

            String filterString = properties.getProperty(RAPID_FILTER_KEY);
            logger.info("load filter string is " + filterString);

            if (filterString != null) {
                String[] filterClassPathArray = filterString.split(RAPID_FILTER_SEPARATOR);
                for (String filterClass : filterClassPathArray) {
                    Class<?> clazz = Class.forName(filterClass);
                    if (RapidFilter.class.isAssignableFrom(clazz)) {
                        repidFilters.add((RapidFilter) clazz.newInstance());
                    }
                }
            }
            return repidFilters;
        } catch (Exception e) {
            logger.error("load rapid filter error, ", e);
            throw e;
        } finally {
            if (is != null) {
                is.close();
            }
        }

    }

}
